package com.sicheng.algorithm.array.sorted;

import java.util.Arrays;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/8/28 10:51
 */
public class MergeSorted {
    public static void main(String[] args) {

        int[] arr = {7,5,6,4};
        mergeSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void mergeSort(int[] arr) {
        if (arr != null && arr.length > 1) {
            mergeSort(arr, 0, arr.length - 1, new int[arr.length]);
        }
    }

    static int count = 0;

    private static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }
    }

    private static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left, j = mid + 1, t = 0;
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j])
                temp[t++] = arr[i++];
            else {
                count += mid - i + 1;
                temp[t++] = arr[j++];
            }
        }
        while (i <= mid)
            temp[t++] = arr[i++];
        while (j <= right)
            temp[t++] = arr[j++];

        t = 0;
        while (left <= right)
            arr[left++] = temp[t++];
    }
}
